package com.moyun.modelclass.fragment;

import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.blankj.utilcode.util.ImageUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.CenterPopupView;
import com.moyun.modelclass.activity.EditModelActivity;
import com.moyun.modelclass.activity.MainActivity;
import com.moyun.modelclass.activity.ModelDetailsActivity;
import com.moyun.modelclass.activity.SubmitOrderActivity;
import com.moyun.modelclass.frank.BaseAdapter;
import com.moyun.modelclass.frank.FFragment;
import com.moyun.modelclass.frank.Http;
import com.moyun.modelclass.http.CommonConfiguration;
import com.moyun.modelclass.http.api.AppModelListApi;
import com.moyun.modelclass.http.api.ShoppingCartListApi;
import com.moyun.modelclass.http.api.ShoppingCartListRemoveApi;
import com.moyun.modelclass.http.bean.ModelResponse;
import com.moyun.modelclass.http.model.HttpData;
import com.moyun.modelclass.R;
import com.moyun.modelclass.databinding.FragmentMainShoppingBinding;
import com.moyun.modelclass.databinding.ItemShoppingCartBinding;
import com.moyun.modelclass.utils.StatusBarUtil;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者：Meteor
 * 日期：2022/1/19 23:25
 * tip：购物车
 */
public class MainShoppingFragment extends FFragment<FragmentMainShoppingBinding> {

    private BaseAdapter<ItemShoppingCartBinding, ModelResponse> adapter;
    private DecimalFormat df = new DecimalFormat("￥##0.00");

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            refresh();
        }
    }

    public void clickCheck() {
        Log.i(TAG, "clickCheck: ");
        if (isEdit) {
            showPop(null);
        } else {
            // TODO: 2024/4/25
            List<String> res = new ArrayList<>();
            for (ModelResponse item : adapter.getData()) {
                if (item.isChecked) {
                    res.add(item.getId());
                }
            }
            if (res.isEmpty()) {
                return;
            }
            SubmitOrderActivity.start(mActivity, res);
        }
    }

    public void clickShopping() {
        Log.i(TAG, "clickShopping: ");
        // TODO: 2024/4/25
        ((MainActivity) mActivity).setTabSelect(0);
    }

    boolean isEdit = false;

    public void clickEdit() {
        Log.i(TAG, "clickEdit: ");
        isEdit = !isEdit;
        if (isEdit) {
            mBinding.editIcon.setText("退出编辑");
            mBinding.tip.setVisibility(View.INVISIBLE);
        } else {
            mBinding.editIcon.setText("编辑");
            mBinding.tip.setVisibility(View.VISIBLE);
        }
        doChange();
        adapter.notifyDataSetChanged();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.d(TAG, "setUserVisibleHint() called with: isVisibleToUser = [" + isVisibleToUser + "]");
        if (isVisibleToUser) {
            refresh();
        }
    }

    private void doChange() {
        List<ModelResponse> dataList = adapter.getData();
        int count = 0;
        double value = 0;
        for (ModelResponse item : dataList) {
            if (item.isChecked) {
                count++;
                value += item.getPrice();
            }
            if (isEdit) {
                item.canDelete = true;
            } else {
                item.canDelete = false;
            }
        }
        if (dataList.size() == 0) {
            isEdit = false;
        }
        mBinding.price.setText(df.format(value * 0.01));
        if (isEdit) {
            mBinding.checkButton.setText("删除(" + count + ")");
        } else {
            mBinding.checkButton.setText("结算(" + count + ")");
        }
    }

    public void onAllSelected(boolean checked) {
        Log.d(TAG, "onAllSelected() called with: checked = [" + checked + "]");
        if (checked) {
            for (ModelResponse shoppingItem : adapter.getData()) {
                shoppingItem.isChecked = true;
            }
            adapter.notifyDataSetChanged();
            doChange();
        } else {
            for (ModelResponse datum : adapter.getData()) {
                datum.isChecked = false;
            }
            adapter.notifyDataSetChanged();
            doChange();
        }
    }


    @Override
    protected void initData() {
        StatusBarUtil.setPaddingSmart(mActivity, mBinding.header);
        mBinding.setPresenter(this);
        adapter = new BaseAdapter<ItemShoppingCartBinding, ModelResponse>() {
            @Override
            protected void onBindData(ModelResponse bean, ItemShoppingCartBinding binding, int position, View itemView) {
                super.onBindData(bean, binding, position, itemView);
                binding.price.setText(df.format(bean.getPrice() * 0.01));
                binding.delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        showPop(bean);
                    }
                });
                binding.checkButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        Log.d(TAG, "onCheckedChanged() called with: compoundButton = [" + compoundButton + "], b = [" + b + "]");
                        bean.isChecked = b;
                        doChange();
                    }
                });
                binding.image.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ModelDetailsActivity.start(mActivity, bean.getId(),false);
                    }
                });

                Glide.with(requireActivity())
                        .asBitmap()
                        .load(CommonConfiguration.splitResUrl(bean.getCoverImage()))
                        .centerInside()
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(new BitmapImageViewTarget(binding.image) {
                            @Override
                            protected void setResource(Bitmap resource) {
                                super.setResource(resource);
                                binding.image.setImageBitmap(ImageUtils.toRoundCorner(resource, 10f));
                            }
                        });
            }
        };
        mBinding.recyclerView.setAdapter(adapter);
        refresh();
    }

    private void refresh() {
        EasyHttp.post(this)
                .api(new ShoppingCartListApi())
                .request(new HttpCallback<HttpData<ShoppingCartListApi.Bean>>(null) {
                    @Override
                    public void onSucceed(HttpData<ShoppingCartListApi.Bean> result) {
                        if (result != null && result.getData() != null && result.getData().modelList.size() > 0) {
                            List<ShoppingCartListApi.ShoppingItem> modelList = result.getData().modelList;
                            if (modelList == null || modelList.isEmpty()) {
                                mBinding.empty.setVisibility(View.VISIBLE);
                                mBinding.recyclerView.setVisibility(View.GONE);
                                mBinding.editIcon.setVisibility(View.GONE);
                            } else {
                                requestDeatil(modelList);
                                mBinding.empty.setVisibility(View.GONE);
                                mBinding.editIcon.setVisibility(View.VISIBLE);
                                mBinding.recyclerView.setVisibility(View.VISIBLE);
                            }
                        } else {
                            mBinding.empty.setVisibility(View.VISIBLE);
                            mBinding.editIcon.setVisibility(View.GONE);
                            mBinding.recyclerView.setVisibility(View.GONE);
                        }
                    }
                });
    }

    private void showPop(ModelResponse bean) {
        String text = "";
        if (bean == null) {
            int count = 0;
            for (ModelResponse modelResponse : adapter.getData()) {
                if (modelResponse.isChecked) {
                    count++;
                }
            }
            if (count == 0) {
                return;
            }
            text = "确认将这" + count + "个模型删除?";
        } else {
            text = "确认删除" + bean.getTitle();
        }
        final String msg = text;
        CenterPopupView popupView = new CenterPopupView(mActivity) {
            @Override
            protected int getImplLayoutId() {
                return R.layout.pop_shopping_cart;
            }

            @Override
            protected void onCreate() {
                findViewById(R.id.dismiss).setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dismiss();
                    }
                });
                ((TextView) findViewById(R.id.text)).setText(msg);
                findViewById(R.id.confirm).setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        List<String> removeIds = new ArrayList<>();
                        if (bean == null) {
                            List<ModelResponse> dataList = adapter.getData();
                            for (int i = dataList.size() - 1; i >= 0; i--) {
                                if (dataList.get(i).isChecked) {
                                    removeIds.add(dataList.get(i).getId());
                                    dataList.remove(i);
                                }
                            }
                        } else {
                            adapter.getData().remove(bean);
                            removeIds.add(bean.getId());
                        }
                        ShoppingCartListRemoveApi requestApi = new ShoppingCartListRemoveApi();
                        requestApi.modelIdList = removeIds;
                        Http.post(mActivity, requestApi, new Http.Callback<ShoppingCartListRemoveApi.Bean>() {
                            @Override
                            public void onSuccess(ShoppingCartListRemoveApi.Bean bean) {
                                clickEdit();
                                if (adapter.getData().size() == 0) {
                                    mBinding.empty.setVisibility(View.VISIBLE);
                                    mBinding.recyclerView.setVisibility(View.GONE);
                                    mBinding.editIcon.setVisibility(View.GONE);
                                } else {
                                    mBinding.empty.setVisibility(View.GONE);
                                    mBinding.editIcon.setVisibility(View.VISIBLE);
                                    mBinding.recyclerView.setVisibility(View.VISIBLE);
                                }
                                dismiss();
                            }
                        });
                    }
                });
            }
        };
        new XPopup.Builder(mActivity).asCustom(popupView).show();
    }

    private void requestDeatil(List<ShoppingCartListApi.ShoppingItem> modelList) {
        if (modelList == null || modelList.isEmpty()) {
            return;
        }
        List<String> ids = new ArrayList<>();
        for (ShoppingCartListApi.ShoppingItem shoppingItem : modelList) {
            if (shoppingItem != null) {
                ids.add(shoppingItem.modelId);
            }
        }
        EasyHttp.post(this)
                .api(new AppModelListApi().setScene(2).setModelIdList(ids))
                .request(new HttpCallback<HttpData<AppModelListApi.Bean>>(null) {
                    @Override
                    public void onSucceed(HttpData<AppModelListApi.Bean> result) {
                        if (result == null || result.getData() == null) {
                            mBinding.empty.setVisibility(View.VISIBLE);
                            mBinding.recyclerView.setVisibility(View.GONE);
                            mBinding.editIcon.setVisibility(View.GONE);
                        }
                        List<ModelResponse> modelList = result.getData().getList();
                        if (modelList == null || modelList.isEmpty()) {
                            mBinding.empty.setVisibility(View.VISIBLE);
                            mBinding.recyclerView.setVisibility(View.GONE);
                            mBinding.editIcon.setVisibility(View.GONE);
                        } else {
                            mBinding.empty.setVisibility(View.GONE);
                            mBinding.editIcon.setVisibility(View.VISIBLE);
                            mBinding.recyclerView.setVisibility(View.VISIBLE);
                            adapter.setData(modelList);
                        }
                    }
                });
    }
}
